import math
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
from rnn_data_load import load_data_time_machine

from custom import train_ch8, predict
from PCA_tools import draw_vocab_pca


# @save
class RNNModel(nn.Module):
    """循环神经网络模型"""

    def __init__(self, rnn_layer, vocab_size, embedding_size, **kwargs):
        super(RNNModel, self).__init__(**kwargs)
        self.rnn = rnn_layer
        self.vocab_size = vocab_size
        self.num_hiddens = self.rnn.hidden_size
        self.embedding_size = embedding_size
        # 新增embeding
        self.embedding = nn.Embedding(vocab_size, embedding_size)
        # 如果RNN是双向的（之后将介绍），num_directions应该是2，否则应该是1
        if not self.rnn.bidirectional:
            self.num_directions = 1
            self.linear = nn.Linear(self.num_hiddens * self.num_directions, self.embedding_size)
        else:
            self.num_directions = 2
            self.linear = nn.Linear(self.num_hiddens * self.num_directions, self.embedding_size)
        self.linear_out = nn.Linear(self.embedding_size, vocab_size)

    def forward(self, inputs, state):
        # X = F.one_hot(inputs.T.long(), self.vocab_size)
        x = inputs.to(torch.long)
        x = self.embedding(x).permute([1, 0, 2])
        # print(x.shape,"T,N,Embedding_size [28, 32, 128]")
        X = x.to(torch.float32)
        # 时间步数*批量大小,词表大小
        Y, state = self.rnn(X, state)
        # 全连接层首先将Y的形状改为(时间步数*批量大小,隐藏单元数)
        # 它的输出形状是(时间步数*批量大小,词表大小)。
        # rnn 的输出仍然遵循 （T,N,H）
        # print(Y.shape,"(Y.shape = [28, 32, 256]")
        output = self.linear(Y.reshape((-1, Y.shape[-1])))
        # print(output.shape, "(output.shape = [896, 128]")
        output = self.linear_out(output)
        # print(output.shape, "(output.shape = [896, 932]")
        return output, state

    def begin_state(self, device, batch_size=1):
        if not isinstance(self.rnn, nn.LSTM):
            # nn.GRU以张量作为隐状态
            return torch.zeros((self.num_directions * self.rnn.num_layers,
                                batch_size, self.num_hiddens),
                               device=device)
        else:
            # nn.LSTM以元组作为隐状态
            return (torch.zeros((
                self.num_directions * self.rnn.num_layers,
                batch_size, self.num_hiddens), device=device),
                    torch.zeros((
                        self.num_directions * self.rnn.num_layers,
                        batch_size, self.num_hiddens), device=device))


# 加载之前准备好的数据
batch_size, num_steps = 32, 28
num_hiddens = 256
embedding_size = 128

train_iter, vocab = load_data_time_machine(batch_size, num_steps)

rnn_layer = nn.RNN(embedding_size, num_hiddens, bidirectional=False)
device = d2l.try_gpu()
net = RNNModel(rnn_layer, vocab_size=len(vocab), embedding_size=embedding_size)
net = net.to(device)
num_epochs, lr = 500, 1
train_ch8(net, train_iter, vocab, lr, num_epochs, device)
print("net.embedding.weight.data 大小", net.embedding.weight.data.shape)
word = "每个"
p_words = predict(word, net, vocab, device)
# [932, 128]
# 降维度加显示
draw_vocab_pca(net.embedding.weight.data, vocab, dim=3)
plt.show()
